package org.atlantis.sbe.lazylib

object lazyLib {

    def delay[A](value: => A): Susp[A] = new SuspImpl[A](value)

    implicit def force[A](s: Susp[A]): A = s()

    abstract class Susp[+A] extends Function0[A]

    class SuspImpl[A](lazyValue: => A) extends Susp[A] {
        private var maybeValue: Option[A] = None

        override def apply() = maybeValue match {
            case None =>
                val value = lazyValue
                maybeValue = Some(value)
                value
            case Some(value) => value
        }

        override def toString() = maybeValue match {
            case None => "Susp(?)"
            case Some(value) => "Susp(" + value + ")"
        }
    }
}

object lazyEvaluation {
    // 要将force转换器引入
    import lazyLib._

    def main(args: Array[String]) {
        val s: Susp[Int] = delay { println("evaluating..."); 5 }
        
        println("s    =" + s) // 还没有进行计算
        println("s+1  =" + (s + 1)) // 隐式使用force，将s计算成int，然后再计算
    }
}